import { DeepseekClient } from './client'
import type { Message, RequestOptions, DeepSeekConvertChunk } from './client'

// 创建Deepseek客户端实例
const deepseekClient = new DeepseekClient()

// 定义请求处理器
interface RequestHandler {
	(req: Request): Promise<Response>
}

// 定义请求体接口
interface ChatRequestBody {
	messages: Message[]
	stream?: boolean
	model?: string
	temperature?: number
	max_tokens?: number
	[key: string]: unknown
}

/**
 * 添加CORS头
 * @param response 响应对象
 * @returns 添加了CORS头的响应对象
 */
function addCorsHeaders(response: Response): Response {
	const headers = new Headers(response.headers)
	headers.set('Access-Control-Allow-Origin', '*')
	headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
	headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')

	return new Response(response.body, {
		status: response.status,
		statusText: response.statusText,
		headers,
	})
}

/**
 * 处理聊天请求
 */
const handleChatRequest: RequestHandler = async (req: Request) => {
	try {
		// 解析请求体
		const body = (await req.json()) as ChatRequestBody
		const { messages, stream = true, ...options } = body

		// 验证消息格式
		if (!Array.isArray(messages) || messages.length === 0) {
			return addCorsHeaders(
				new Response(JSON.stringify({ error: '无效的消息格式' }), {
					status: 400,
					headers: { 'Content-Type': 'application/json' },
				}),
			)
		}

		// 处理流式请求
		if (stream) {
			// 创建一个可读流
			const { readable, writable } = new TransformStream()
			const writer = writable.getWriter()
			const encoder = new TextEncoder()

			// 发送流式请求
			deepseekClient
				.chatStream(messages, options as RequestOptions, (chunk: DeepSeekConvertChunk) => {
					// 将每个块写入流
					const data = JSON.stringify(chunk) + '\n'
					writer.write(encoder.encode(data))
				})
				.then(() => writer.close())
				.catch((error) => {
					console.error('流式请求处理错误:', error)
					writer.abort(error)
				})

			// 返回流式响应
			return addCorsHeaders(
				new Response(readable, {
					headers: {
						'Content-Type': 'text/event-stream',
						'Cache-Control': 'no-cache',
						Connection: 'keep-alive',
					},
				}),
			)
		} else {
			// 处理非流式请求
			const content = await deepseekClient.chat(messages, options as RequestOptions)
			return addCorsHeaders(
				new Response(JSON.stringify({ content }), {
					headers: { 'Content-Type': 'application/json' },
				}),
			)
		}
	} catch (error) {
		console.error('请求处理错误:', error)
		return addCorsHeaders(
			new Response(JSON.stringify({ error: '请求处理失败' }), {
				status: 500,
				headers: { 'Content-Type': 'application/json' },
			}),
		)
	}
}

/**
 * 启动HTTP服务器
 */
export function startServer(port: number = 3000) {
	console.log(`启动 Deepseek API 代理服务器，端口: ${port}`)

	return Bun.serve({
		port,
		async fetch(req) {
			const url = new URL(req.url)

			// 处理预检请求
			if (req.method === 'OPTIONS') {
				return addCorsHeaders(new Response(null, { status: 204 }))
			}

			// 健康检查端点
			if (url.pathname === '/health') {
				return addCorsHeaders(
					new Response(JSON.stringify({ status: 'ok' }), {
						headers: { 'Content-Type': 'application/json' },
					}),
				)
			}

			// 聊天端点
			if (url.pathname === '/v1/chat/completions' && req.method === 'POST') {
				return handleChatRequest(req)
			}

			// 404 - 未找到
			return addCorsHeaders(new Response('Not Found', { status: 404 }))
		},
	})
}
